package com.share.interceptor;

import com.share.utils.MyJWTUtil;
import com.share.utils.UserUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Slf4j
public class SecurityInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("Intercepted request to URL: {}", request.getRequestURI());
        String token = request.getHeader("authorization");

        //判断请求方式，排除OPTIONS请求
        if(request.getMethod().toUpperCase().equals("OPTIONS")){
            return true;    //通过所有OPTION请求
        }

        // 1. 拿到 token 中的字段进行校验
        Long userId = MyJWTUtil.getUserId(token);
        log.info("userId:{}",userId);
        if (userId == null) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid token");
            return false;       // 直接返回错误信息 不继续该拦截器的后续逻辑
        }

        // 2. 验证是否为二次登录
        String redisToken = (String) redisTemplate.opsForValue().get("tokens:" + userId);
        if (!token.equals(redisToken)) {         // 第一次登录时 token 是一致的 不一致则说明二次登录了
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Duplicate login detected");
            return false;
        }

        // 3. 存储用户 id 到 ThreadLocal
        UserUtils.set(userId);
//        HttpSession session = request.getSession();
//        session.setAttribute("user", user);

        // 4. 上述校验通过 放行 继续后续拦截器
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
